package com.ykefu.assign.netty.netty.websocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author likai
 * @date 2020/4/18 19:12
 * @email likai@7moor..com
 * @desc
 */
public class ChannelManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(ChannelManager.class);


    static final ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    static final ConcurrentMap<String, Channel> channels = new ConcurrentHashMap<>();

    public void save(String connectId,ChannelHandlerContext ctx){
        group.add(ctx.channel());
        channels.put(connectId,ctx.channel());
    }

    public void delChannel(ChannelHandlerContext ctx) {
        for(Map.Entry<String,Channel> entry:channels.entrySet()){
            Channel value = entry.getValue();
            if(ctx.channel().equals(value)){
                String key = entry.getKey();
                boolean remove1 = channels.remove(key, entry.getValue());
                if(remove1) {
                    LOGGER.info("remove success --> connectUUid:{}",key);
                }
            }
        }
        LOGGER.info("channels:{},group:{}",channels.size(),group.size());
    }


    private ChannelManager(){
    }

    public static ChannelManager getInstance(){
        return InnerChannelManager.instance;
    }

    private static class InnerChannelManager{
        private static ChannelManager instance = new ChannelManager();
    }


}
